import csv
# 初始化电话簿文件（确保包含标题行）
def init_phonebook():
        with open("denwa.csv", "w", encoding="utf-8", newline='') as f:
            writer = csv.writer(f)
            # 写入标题行
            writer.writerow(["姓名", "电话号码", "地址"])
            # 写入初始数据
            writer.writerows([
                ["赵三", 18434795720, "临汾"],
                ["钱三", 18434795721, "运城"],
                ["孙三", 18434795722, "贵州"],
                ["李三", 18434795723, "成都"],
                ["周三", 18434795724, "重庆"],
                ["吴三", 18434795725, "大同"],
                ["郑三", 18434795726, "郑州"],
                ["王三", 18434795727, "西安"]
            ])


# 查看所有信息
def listphones():
    print("\n=== 电话簿列表 ===")
    with open("denwa.csv", "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            print(f"{row['姓名']}：{row['电话号码']}\t{row['地址']}")
    print("=================\n")


# 查看单个电话信息
def showphone(name):
    found = False
    with open("denwa.csv", "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            if row["姓名"] == name:
                print("\n=== 联系人信息 ===")
                print(f"姓名：{row['姓名']}")
                print(f"电话：{row['电话号码']}")
                print(f"地址：{row['地址']}")
                print("=================\n")
                found = True
                break

    if not found:
        print(f"\n⚠️ 未找到姓名为 [{name}] 的联系人\n")


# 根据姓名删除信息
def delete(name):
    rows = []
    # 读取所有数据
    with open("denwa.csv", "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        fieldnames = reader.fieldnames
        for row in reader:
            if row["姓名"] != name:
                rows.append(row)

    # 写回文件
    with open("denwa.csv", "w", encoding="utf-8", newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

    print(f"\n✅ 已删除姓名为 [{name}] 的联系人\n" if len(rows) < 8 else
          f"\n⚠️ 未找到姓名为 [{name}] 的联系人\n")


# 修改联系人信息
def change(name, new_name=None, new_phone=None, new_address=None):
    rows = []
    updated = False
    # 读取所有数据
    with open("denwa.csv", "r", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        fieldnames = reader.fieldnames
        for row in reader:
            if row["姓名"] == name:
                # 更新字段
                if new_name: row["姓名"] = new_name
                if new_phone: row["电话号码"] = new_phone
                if new_address: row["地址"] = new_address
                updated = True
            rows.append(row)

    # 写回文件
    with open("denwa.csv", "w", encoding="utf-8", newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

    if updated:
        print("\n✅ 联系人信息已更新\n")
    else:
        print(f"\n⚠️ 未找到姓名为 [{name}] 的联系人\n")


# 添加联系人
def add(name, phone, address):
    with open("denwa.csv", "a", encoding="utf-8", newline='') as f:
        writer = csv.DictWriter(f, fieldnames=["姓名", "电话号码", "地址"])
        writer.writerow({"姓名": name, "电话号码": phone, "地址": address})
    print(f"\n✅ 已添加联系人 [{name}]\n")


# 主菜单系统
def main():
    init_phonebook()  # 初始化电话簿
    print("\n======= 欢迎进入电话簿系统 =======")

    while True:
        print("1. 查看所有电话信息")
        print("2. 查看单个电话信息")
        print("3. 根据姓名删除信息")
        print("4. 根据姓名修改信息")
        print("5. 添加电话信息")
        print("6. 退出系统")

        choice = input("\n请选择操作 (1-6): ").strip()

        if choice == '1':
            listphones()
        elif choice == '2':
            name = input("请输入需要查看的姓名: ").strip()
            showphone(name)
        elif choice == '3':
            name = input("请输入需要删除的姓名: ").strip()
            delete(name)
        elif choice == '4':
            name = input("请输入需要修改的姓名: ").strip()
            # 先显示当前信息
            showphone(name)

            # 获取新信息
            new_name = input("新姓名 (留空保持不变): ").strip() or None
            new_phone = input("新电话号码 (留空保持不变): ").strip() or None
            new_address = input("新地址 (留空保持不变): ").strip() or None

            if any([new_name, new_phone, new_address]):
                change(name, new_name, new_phone, new_address)
            else:
                print("\n⚠️ 未修改任何信息\n")
        elif choice == '5':
            name = input("请输入姓名: ").strip()
            phone = input("请输入电话号码: ").strip()
            address = input("请输入地址: ").strip()
            add(name, phone, address)
        elif choice == '6':
            print("\n感谢使用电话簿系统，再见！\n")
            break
        else:
            print("\n⚠️ 无效选择，请重新输入\n")


if __name__ == "__main__":
    main()